class UsersController < ApplicationController
  filter_access_to :all
  before_filter :require_no_user, :only => [:new, :create]
  before_filter :require_user, :only => [:edit, :update, :destroy]

  #
  def show
    @user = User.find(params[:id])
    store_location
  end

  #
  def new
    @user = User.new
  end
 
  #
  def create
    @user = User.new(params[:user])

    if @user.save_without_session_maintenance
      @user.roles << Role.user_role
      @user.deliver_activation_instructions!
      flash[:notice] = "Your account has been created. Please check your e-mail for your account activation instructions."
      redirect_to root_url 
    else
      render :action => :new
    end
  end

  #
  def edit
    @user = @current_user 
  end

  #
  def update
    @user = @current_user
    if @user.update_attributes(params[:user])
      flash[:notice] = "Successfully updated user"
      redirect_to root_url
    else
      render :action => 'edit'
    end
  end

  #
  def resend_activation
    if params[:email]
      @user = User.find_by_email params[:email]
      if @user && !@user.active?
        @user.deliver_activation_instructions!
        flash[:notice] = "Please check your email for your "+
        " account acitvation instructions."
        redirect_to root_path
      elsif @user && @user.active?
        flash[:notice] = "This account is already active."
        redirect_to root_path
      end
    end
  end

  #
  def admin_reset_password
    @user = User.find_by_username(params[:username])
    @user.deliver_password_reset_instructions!
    
    redirect_to admin_interface_path  
  end

  #
  def destroy
    @user = User.find(params[:id])
    
    User.transaction do
      #Delete all associations
      @user.forum_threads.each do |thread|
        thread.user_id = 7
        thread.save
      end
      @user.posts.each do |post|
        post.user_id = 7
        post.save
      end
      @user.assignments.each do |assignment|
        assignment.destroy
      end

      @user.destroy
      flash[:notice] = "User Successfully deleted."
    end
    redirect_to_request_uri
  end
end
